<?php

namespace app\api\controller\store;

use app\admin\model\Financialrecords;
use app\admin\model\join\Merchant;
use app\admin\model\store\Bank;
use app\admin\model\store\Withdrawal;
use app\api\model\JoinMerchant;
use app\api\model\User;
use app\common\controller\Api;
use think\Request;


class Store extends Api
{
    protected $noNeedRight = '*';
    protected $noNeedLogin = ['store_index','store_settings','store_information','login_passwords'];
    protected $store_id;


    public function __construct(Request $request = null)
    {
        parent::__construct($request);
//        var_dump($this->auth->id);die;
        $this->store_id=JoinMerchant::where(['user_id'=>$this->auth->id])->value('id');
//
    }

    /**
     * @param Request $request
     * 商家首页信息
     * api/store/store/store_index
     * @return \think\response\Json
     * @throws \think\Exception
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     *
     */
    public function store_index(Request $request)
    {
          $post=$request->post();
          $store=Merchant::where(['id'=>$post['store_id']])->field('id,trade_name,avatar,star,my_assets,withdrawable,withdrawn')->find()->toArray();
          if($store){
              $store['avatar']=yuming($store['avatar']);
          }
          return  json(['code'=>200,'msg'=>'请求成功','data'=>$store]);
    }

    /**
     * @param Request $request
     * 店铺设置
     * api/store/store/store_settings
     * @return \think\response\Json|void
     * @throws \think\Exception
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function store_settings(Request $request)
    {
        $post=$request->post();
        if($post['type']==1){
            $store=Merchant::where(['id'=>$post['store_id']])->field('id,trade_name,avatar,phone,join_type_id,address')->find()->toArray();
            if($store){
                $store['avatar']=yuming($store['avatar']);
            }
            return  json(['code'=>200,'msg'=>'请求成功','data'=>$store]);
        }
        if($post['type']==2){
             $data=[
                  'trade_name'=>$post['trade_name'],
                  'avatar'=>$post['avatar'],
                  'phone'=>$post['phone'],
                  'join_type_id'=>$post['join_type_id'],
                  'address'=>$post['address'],
             ];
            $insert=Merchant::where(['id'=>$post['store_id']])->update($data);
            if($insert){
                return  json(['code'=>200,'msg'=>'修改成功','data'=>'']);
            }else{
                return  json(['code'=>200,'msg'=>'暂无修改','data'=>'']);
            }
        }
    }

    /**
     * @param Request $request
     * 我的-设置-店铺信息
     * api/store/store/store_information
     * @return \think\response\Json
     * @throws \think\Exception
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function store_information(Request $request)
    {
        $post=$request->post();
        $store=Merchant::where(['id'=>$post['store_id']])->field('id,trade_name,business_image,phone,my_assets,join_type_id,address,business_image,id_card_front_image,id_card_back_image')->find()->toArray();
        if($store){
            $store['business_image']=yuming($store['business_image']);
            $store['id_card_front_image']=yuming($store['id_card_front_image']);
            $store['id_card_back_image']=yuming($store['id_card_back_image']);
        }
        return  json(['code'=>200,'msg'=>'请求成功','data'=>$store]);

    }

    /**
     * @param Request $request
     * 我的-设置-登录密码已设置
     * store/store/login_passwords
     * @return \think\response\Json
     * @throws \think\Exception
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function login_passwords(Request $request)
    {
        $post=$request->post();
        $store=JoinMerchant::where(['id'=>$this->store_id])->find()->toArray();
        if($store['login_passwords']!=md5(md5($post['y_password']))){
                return  json(['code'=>404,'msg'=>'原密码错误']);
        }
        if($post['y_passwords']!=$post['q_password']){
            return  json(['code'=>404,'msg'=>'修改密码与确认密码不一致']);
        }
        $up=JoinMerchant::where(['id'=>$this->store_id])->update(['login_passwords'=>md5(md5($post['y_password']))]);
        if($up){
            return  json(['code'=>200,'msg'=>'已修改','data'=>'']);
        }
    }

    /**
     * @param Request $request
     * 我的-设置-登录密码未设置
     * store/store/login_set
     * @return \think\response\Json
     * @throws \think\Exception
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function login_set(Request $request)
    {

        $post=$request->post();
        $code=200;
//        $store=JoinMerchant::where(['id'=>$this->store_id])->find()->toArray();
        if($code!=$post['code']){
            return  json(['code'=>404,'msg'=>'验证码错误']);
        }
        if($post['y_passwords']!=$post['q_password']){
            return  json(['code'=>404,'msg'=>'修改密码与确认密码不一致']);
        }
        $up=JoinMerchant::where(['id'=>$this->store_id])->update(['login_passwords'=>md5(md5($post['y_password']))]);
        if($up){
            return  json(['code'=>200,'msg'=>'已设置','data'=>'']);
        }
    }

    /**
     * @param Request $request
     * 我的-设置-发送验证码
     * store/store/send_verification_code
     * @return \think\response\Json
     * @throws \think\Exception
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function send_verification_code(Request $request)
    {
        $this->success("暂未设置");
        $mobile=$request->post('mobile');
        if (\sms\Sms::sendCode($mobile)) {
            $this->success("发送成功");
        }
    }

    /**
     * 绑定银行卡
     * store/store/add_bank_card
     * @param Request $request
     * @return \think\response\Json|void
     * @throws \think\Exception
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     *
     */
    public function add_bank_card(Request $request)
    {
        $POST=$request->post();
        $find=Bank::where(['bank_card_number'=>$POST['bank_card_number'],'store_id'=>$this->store_id])->find()->toArray();
        if($find){
            return  json(['code'=>404,'msg'=>'该银行卡已绑定','data'=>'']);
        }
        $data=[
            'name'=>$POST['name'],
            'bankid'=>$POST['bankid'],
            'bankname'=>$POST['bankname'],
            'bank_card_number'=>$POST['bank_card_number'],
            'mobile'=>$POST['mobile'],
            'user_id'=>$this->auth->id,
            'store_id'=>$this->store_id,
            'createtime'=>time()
        ];
       $in=Bank::create($data);
       if($in){
           return  json(['code'=>200,'msg'=>'添加成功','data'=>'']);
       }
    }


    /**
     * 开户银行列表
     * store/store/bank_list
     * @param Request $request
     * @return \think\response\Json|void
     * @throws \think\exception\DbException
     *
     */
    public  function  bank_list(Request $request)
    {
        $POST=$request->post();
        $bank= \app\admin\model\Bank::where(['switch'=>1])->select();
        if($bank){
            $bank=$bank->toArray();
            foreach ($bank as &$value){
                $value['image']=yuming($value['image']);
            }
        }
       return  json(['code'=>200,'msg'=>'请求成功','data'=>'']);


    }


    /**
     * 数据统计
     * store/store/data_statistics
     * @param Request $request
     * @return \think\response\Json
     * @throws \think\Exception
     *
     */
    public  function  data_statistics(Request $request)
    {
            $post=$request->post();
            $where['store_id']=$this->store_id;
            if($post['type']==1){
                $start=strtotime($post['start']);
                $end=strtotime($post['end']);
                $where['createtime']=['between', [$start, $end,'AND']];
            }
            if($post['type']==2){
                $start=strtotime($post['start']);
                $end=strtotime($post['end']);
                $where['createtime']=['between', [$start, $end,'AND']];
            }

           //收益统计

           //今日退款
           $data['revenue_statistics']['today_money']=\app\api\model\Order::where($where)->sum('actual_price');
           //昨日全天
           $data['revenue_statistics']['yesterday_money']=\app\api\model\Order::whereTime('createtime','yesterday')->sum('actual_price');
           //昨日此刻
           $data['revenue_statistics']['yesterday_cs_money']=\app\api\model\Order::where($where)->sum('actual_price');

           //支付人数
           $data['revenue_statistics']['zf_people']=\app\api\model\Order::where($where)->where(['order_status'=>1])->count();
           //订单笔数
           $data['revenue_statistics']['zf_count']=\app\api\model\Order::where($where)->count();
           //待入帐
           $data['revenue_statistics']['to_be_credited']=\app\api\model\Order::where($where)->where(['order_status'=>2])->sum('actual_price');
           //待支付
           $data['revenue_statistics']['to_be_paid']=\app\api\model\Order::where($where)->where(['order_status'=>0])->sum('actual_price');
           //待发货
           $data['revenue_statistics']['to_be_shipped']=\app\api\model\Order::where($where)->where(['order_status'=>1])->sum('actual_price');
           //客单价
            if($data['revenue_statistics']['zf_people']>0){
                $data['revenue_statistics']['customer_unit_price']=$data['revenue_statistics']['today_money']/$data['revenue_statistics']['zf_people'];
            }else{
                $data['revenue_statistics']['customer_unit_price']=0;
            }


           //售后统计

           //今日退款
           $data['after_sales_statistics']['todays_refund']=\app\api\model\Order::where($where)->where(['aftersale_status'=>1])->sum('actual_price');
           //昨日全天
           $data['after_sales_statistics']['refund_yesterday']=\app\api\model\Order::whereTime('createtime','yesterday')->where(['aftersale_status'=>1])->sum('actual_price');;
           //昨日此刻
           $data['after_sales_statistics']['yesterday_at_this_moment']=\app\api\model\Order::where($where)->where(['aftersale_status'=>1])->sum('actual_price');;

           //退款人数
           $data['after_sales_statistics']['number_of_refunds']=\app\api\model\Order::where($where)->where(['aftersale_status'=>['gt',0]])->count();
           //退款笔数
           $data['after_sales_statistics']['Number_of_count']=\app\api\model\Order::where($where)->where(['aftersale_status'=>['gt',0]])->count();
           //待退款
           $data['after_sales_statistics']['pending_refund']=\app\api\model\Order::where($where)->where(['aftersale_status'=>1])->sum('actual_price');
           //客单价
           if($data['after_sales_statistics']['number_of_refunds']>0){
               $data['after_sales_statistics']['customer_unit_price']=$data['after_sales_statistics']['todays_refund']/$data['after_sales_statistics']['number_of_refunds'];
           }else{
                $data['after_sales_statistics']['customer_unit_price']=0;
           }

           return  json(['code'=>200,'msg'=>'请求成功','data'=>$data]);
    }

    /**
     * @return void
     *
     *  商家钱包金额
     *  store/store/my_wallet
     */
    public function my_wallet(Request  $request){

         $data=Merchant::where(['id'=>$this->store_id])->field('id,my_assets,withdrawable,withdrawn')->find();
         if($data){
             $data=$data->toArray();
         }
         return  json(['code'=>200,'msg'=>'请求成功','data'=>$data]);
    }

    /**
     * 商家资产列表
     * store/store/financialrecords_list
     * @param Request $request
     * @return \think\response\Json
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     *
     */
    public function  financialrecords_list(Request  $request){
         $post=$request->post();
         $data=Financialrecords::where(['store_id'=>$this->store_id])->field('id,money,type,image,order,createtime')->page($post['page'],$post['pagesize'])->order('createtime desc')->select();
         if($data){
             $data=yuming($data->toArray(),'image');
             foreach ($data as &$value){
                 $value['createtime']=date('Y-m-d H:i:s',$value['createtime']);
             }
         }

        return  json(['code'=>200,'msg'=>'请求成功','data'=>$data]);

    }

    /**
     * 商家提现
     * store/store/store_withdrawal
     * @param Request $request
     * @return \think\response\Json|void
     * @throws \think\Exception
     *
     */
    public function store_withdrawal(Request  $request){
        $post=$request->post();
        $data=[
             'user_id'=>$this->auth->id,
             'store_id'=>$this->store_id,
             'money'=>$post['money'],
             'store_bank_id'=>$post['store_bank_id'],
             'createtime'=>time(),
        ];
        $data=Withdrawal::create($data);
        $setDec=JoinMerchant::where(['id'=>$post['store_id']])->setDec('my_assets',$post['money']);
        $setInc=JoinMerchant::where(['id'=>$post['store_id']])->setInc('withdrawns',$post['money']);
        if($data&&$setDec&&$setInc){
            return  json(['code'=>200,'msg'=>'提交成功，等待后台审核','data'=>'']);
        }
    }

}